package com.burial.controller;

import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePayRequest;
import com.burial.bo.OrderProductBo;
import com.burial.common.result.Result;
import com.burial.config.AlipayConfig;
import com.burial.dto.OrderDTO;
import com.burial.entity.Order;
import com.burial.service.OrderInfoService;
import com.burial.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
public class AlipayController {
    private static final String GATEWAY_URL="https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT="JSON";
    private static final String CHARSET="UTF-8";
    private static final String SING_TYPE="RSA2";

    @Autowired
    private AlipayConfig alipayConfig;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderInfoService orderInfoService;

    @GetMapping("/pay")
    public void pay(Integer oid, HttpServletResponse httpResponse)throws Exception{
        //查询订单
        OrderDTO orderDTO = orderInfoService.findOrderInfo(oid);

        if (orderDTO==null)return;

        Double money=0.0;
        for (OrderProductBo orderProductBo : orderDTO.getOrderInfoList()) {
            money+=orderProductBo.getProduct().getPrice()*orderProductBo.getPcount();
        }
        if (money==0){
            return;
        }

        //创建Client，通过SDK提供的Client，负责调用支付宝的API
        DefaultAlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, alipayConfig.getAppId(),
                alipayConfig.getAppPrivateKey(), FORMAT, CHARSET, alipayConfig.getAlipayPublicKey(), SING_TYPE);

        //创建Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();//发送请求的Request类
        request.setNotifyUrl(alipayConfig.getNotifyUrl());
        JSONObject bizContent = new JSONObject();
        bizContent.set("out_trade_no",oid);//订单编号
        bizContent.set("total_amount",money);//订单总金额
        bizContent.set("subject",oid);//支付名称
        bizContent.set("product_code","FAST_INSTANT_TRADE_PAY");  //固定写法

        request.setBizContent(bizContent.toString());

        request.setReturnUrl("http://localhost:8080/doc.html");//支付完成后跳转的地址


        //执行请求，拿到响应的结果，返回给浏览器
        String form="";
        try {
            form=alipayClient.pageExecute(request).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        httpResponse.setContentType("text/html;charset="+CHARSET);
        httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();

    }
    @PostMapping("/notify")
    public void payNotify(HttpServletRequest request)throws Exception{


        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")){



            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name,request.getParameter(name));
            }

            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, alipayConfig.getAlipayPublicKey(), "UTF-8");

            if (checkSignature){



                String tradeNo = params.get("out_trade_no");//订单编号
                String gmtPayment = params.get("gmt_payment");//支付时间
                String alipayTradeNo = params.get("trade_no");//支付宝交易编号

                //更新订单状态为已支付，设置支付信息
                orderService.updateState(Long.parseLong(tradeNo),2);
            }
        }
    }


}
